<template>
	<van-action-sheet
		v-model:show="apply.visible"
		style="min-height: 100%; max-height: 100%;"
		:title="detail.id ? '编辑会议' : '申请会议'"
		:close-on-click-overlay="false"
		:round="false"
	>
		<van-form ref="refForm" @submit="clickSubmit">
			<van-cell-group inset>
				<van-field
					v-model="params.topic"
					label="会议主题"
					placeholder="请输入会议主题"
					:rules="[{ required: true, message: '请输入会议主题' }]"
				/>

				<van-field
					v-model="params.meetingDate"
					label="会议日期"
					placeholder="请选择会议日期"
					readonly
					:rules="[{ required: true, message: '请选择会议日期' }]"
					@click="dateTime.visible = true"
				/>
				<van-action-sheet
					:closeable="false"
					:round="false"
					:close-on-click-overlay="false"
					v-model:show="dateTime.visible"
				>
					<van-date-picker
						title="选择日期"
						:min-date="new Date()"
						@confirm="clickConfirmMeetingDate"
						@cancel="dateTime.visible = false"
					/>
				</van-action-sheet>
				<van-field
					v-model="params.meetingTime"
					label="会议时间"
					placeholder="请选择会议开始时间"
					readonly
					:rules="[{ required: true, message: '请选择会议开始时间' }]"
					@click="dateTime.timeVisible = true"
				/>
				<van-action-sheet
					:closeable="false"
					:round="false"
					:close-on-click-overlay="false"
					v-model:show="dateTime.timeVisible"
				>
					<van-time-picker
						v-model="currentTime"
						title="选择时间"
						:columns-type="['hour', 'minute']"
						@cancel="dateTime.timeVisible = false"
						@confirm="clickConfirmMeetingTime"
					/>
				</van-action-sheet>
				<van-field
					label="会议形式"
					name="radio"
					:rules="[{ required: true, message: '请选择会议形式' }]"
				>
					<template #input>
						<van-radio-group v-model="params.type" direction="horizontal">
							<van-radio v-if="meetingSetting.allowOnline != 1" :name="0">线下会</van-radio>
							<van-radio v-if="meetingSetting.allowOnline != 2" :name="1">线上会</van-radio>
						</van-radio-group>
					</template>
  				</van-field>

				  <van-field
				  	v-if="params.type === 0"
				  	v-model="params.meetingAddr"
					label="会议地址"
					placeholder="请输入会议地址"
					:rules="[{ required: true, message: '请输入会议地址' }]"
				></van-field>

				<template v-for="(item, index) in params.roles" :key="item.roleId">
					<div v-for="(val, idx) in item.list">
						<van-field
							:model-value="val ? val.speakerName : ''"
							:label="item.roleName + (idx || '')"
							:placeholder="`请选择${item.roleName}`"
							readonly
							:rules="[{ required: true, message: `请选择${item.roleName}` }]"
							@click="clickSelectSpeaker(item, index, idx)"
						>
							<template #button>
								<van-icon
									@click.stop.prevent="clickAddRole(item, index)"
									size="26"
									name="add-o"
									v-show="idx === (item.list.length - 1)"
								/>
								<van-icon
									@click.stop.prevent="clickRemoveRole(item, index, idx)"
									size="26"
									name="close"
									v-show="item.list.length > 1"
								/>
							</template>
						</van-field>
						<van-field
							v-if="item.roleId === 1"
							v-model="val.speakerTopic"
							:label="`讲题${idx || ''}`"
							placeholder="请选择讲题"
							readonly
							@click="selectTopicRef.init();speaker.handleIndex=index;speaker.handleItemIndex=idx"
							:rules="[{ required: true, message: '请选择讲题' }]"
						/>
						<van-field
							v-if="item.roleId === 1"
							:columns-type="['hour', 'minute']"
							:model-value="val ? val.speakerTimeRange : ''"
							:label="`时间${idx || ''}`"
							readonly
							placeholder="请选择时间"
							@click="clickSelectSpeakerTimeRange(item, index, idx)"
							:rules="[{ required: true, message: '请选择时间' }]"
						/>
					</div>
				</template>
				<van-action-sheet
					:closeable="false"
					:round="false"
					style="min-height: 100%; max-height: 100%;"
					@opened="timeRangePickerOpened"
					v-model:show="speaker.visible"
				>
					<select-speaker :list="speaker.list" @selected="clickConfirmSpeaker"></select-speaker>
				</van-action-sheet>

				<select-topic :speakerIndex="speaker.handleItemIndex" :roleIndex="speaker.handleIndex" ref="selectTopicRef" @selected="onTopicSelected"></select-topic>

				<van-action-sheet
					:closeable="false"
					:round="false"
					@opened="timeRangePickerOpened"
					:close-on-click-overlay="false"
					v-model:show="speaker.timeRangeVisible"
				>
					<van-picker-group
						title="时间"
						next-step-text="结束时间"
						:tabs="['开始时间', '结束时间']"
						@confirm="onSpeakerTimeRangeConfirm"
						@cancel="speaker.timeRangeVisible = false"
						>
						<van-time-picker v-model="startTime" />
						<van-time-picker v-model="endTime" />
					</van-picker-group>
				</van-action-sheet>

				<!-- <van-action-sheet
					:closeable="false"
					:round="false"
					:close-on-click-overlay="false"
					v-model:show="speaker.visible"
				>
					<van-picker
						title="选择讲者"
						:columns="speaker.list"
						@confirm="clickConfirmSpeaker"
						@cancel="clickCancelSpeaker"
					/>
				</van-action-sheet> -->
			</van-cell-group>

			<div style="margin: 16px;">
				<van-button size="small" block type="primary" class="mt-3" native-type="submit">提交</van-button>
			</div>
		</van-form>
	</van-action-sheet>

	<div class="vol_create van-safe-area-bottom"></div>
	<div class="vol_create foot van-safe-area-bottom">
		<div>
			<van-button
				size="small"
				type="primary"
				block
				class="mt-3"
				@click="clickApplyMeeting"
			>申请会议</van-button>
		</div>
	</div>
</template>

<script setup>
import { useStore } from 'vuex';
import { ref, reactive, inject, watch } from "vue";
import { showToast, showConfirmDialog } from 'vant';
import moment from 'moment';

const emits = defineEmits(['refresh']);

const api = inject('api')
const store = useStore()
const selectTopicRef = ref(null)
// selectTopicRef.value.init()

const detail = ref({})
const currentTime = ref(['17', '00'])
const startTime = ref(['17', '00'])
const endTime = ref(['17', '20'])
const timeSelected = ref(0)
const speakerSelVisible = ref(false)

watch(startTime, (newValue, oldValue) => {
  let curMo = moment('1989-06-18 ' + newValue[0]+ ':' + newValue[1] + ':00' )
  let endMo = curMo.add(25, 'minutes').format('HH:mm')
  endTime.value = [endMo.split(':')[0], endMo.split(':')[1]]
});


const apply = reactive({
	visible: false
})
const meetingSetting = ref({})

const params = reactive({
	topic: '',
	meetingDate: '',
	meetingTime: '',
	type: '',
	meetingAddr: '',
	roles: []
})

const speaker = reactive({
	list: [],
	visible: false,
	timeRangeVisible: false,
	timeRangeItem: null,
	handleItem: null,
	handleItemIndex: -1,
	handleIndex: -1
})
const dateTime = reactive({
	visible: false,
	timeVisible: false
})

const timeRangePickerOpened = () =>{
	if(timeSelected.value !== 0) {
		startTime.value = endTime.value
	}
}

// 获取会议设置
const getMeetingSetting = async () => {
	const res = await api.meetingGetSetting(detail.value.projectId || store.getters['user/getUserInfo'].projectId)
	if (!res.code) {
		meetingSetting.value = JSON.parse(res.data)
		params.roles = (meetingSetting.value.roleSetting || []).map(item => ({
			...item,
			list: [{}]
		}))
		timeSelected.value = 0

    if (detail.value.id) {
      const speakerArr = JSON.parse(detail.value.speakerJson)
      params.roles.forEach(item => {
        item.list = []
        speakerArr.forEach(val => {
          if (item.roleId === val.roleId) {
            item.list.push(val)
          }
        })
      })
    }
	}
}

/**
 * 选择讲题
 * 选择讲题后将时间设置上
 **/
const onTopicSelected = (item) => {
	console.log(params.roles)
	params.roles[item.roleIndex].list[item.speakerIndex].speakerTopic = item.topic
	if( startTime.value ) {
		let curMo = moment('1989-06-18 ' + startTime.value[0]+ ':' + startTime.value[1] + ':00' )
		let endMo = curMo.add(item.timeRange, 'minutes').format('HH:mm')
		endTime.value = [endMo.split(':')[0], endMo.split(':')[1]]
		params.roles[item.roleIndex].list[item.speakerIndex].speakerTimeRange = startTime.value.join(':')+ '-' +endTime.value.join(':')
	}
}

// 获取讲者列表
const getSpeakerList = async () => {
	const res = await api.speakerList({
		limit: 99999,
    	isAll: true,
		page: 1,
		status: 1
	})
	if (!res.code) {
		speaker.list = res.data.map(item => ({
			...item,
			text: item.name,
			value: item.id
		}))
	}
}
// 添加角色
const clickAddRole = (item, index) => {
	if (item.list.length >= item.max) {
		showToast(`${item.roleName}已达最大数量`)
		return
	}
	item.list.push({})
	params.roles[index] = item
}
// 删除角色
const clickRemoveRole = (item, index, idx) => {
	if (item.list.length <= 1) {
		showToast(`无法再删除了`)
		return
	}
	item.list.splice(idx, 1)
	params.roles[index] = item
}
// 选择讲者
const clickSelectSpeaker = (item, index, idx) => {
	speaker.handleItem = item
	speaker.handleItemIndex = index
	speaker.handleIndex = idx
	speaker.visible = true
}

// 取消选择
const clickCancelSpeaker = () => speaker.visible = false
// 确认选择讲者
const clickConfirmSpeaker = (sp) => {
	console.log(sp)
	const isExist = speaker.handleItem.list.some(item => item.speakerId === sp.id)
	if (isExist) {
		showToast(`该${speaker.handleItem.roleName}已被选择`)
		return
	}
	speaker.handleItem.list.forEach((item, index) => {
		if(index === speaker.handleIndex) {
			speaker.handleItem.list[index] = {
				...item,
				avatar: sp.avatar,
				speakerId: sp.id,
				speakerName: sp.name,
				hospital: sp.hospital,
				department: sp.department
			}
		}
	})
	params.roles[speaker.handleItemIndex] = speaker.handleItem
	clickCancelSpeaker()
}
//选择讲者的讲题开始和结束时间
const clickSelectSpeakerTimeRange = (item, index, idx) => {
	speaker.handleItem = item
	speaker.handleItemIndex = index
	speaker.handleIndex = idx
	speaker.timeRangeVisible = true
}
const onSpeakerTimeRangeConfirm = (val, idx) => {
	let selectRange = `${val[0].selectedValues[0]}:${val[0].selectedValues[1]}-${val[1].selectedValues[0]}:${val[1].selectedValues[1]}`
	if(speaker.handleItem.list.length === 0) {
		speaker.handleItem.list[speaker.handleIndex] = {speakerTimeRange: selectRange}
		return false
	}
	speaker.handleItem.list.forEach((item, index) => {
		if(index === speaker.handleIndex) {
			speaker.handleItem.list[index] = {
				...item,
				speakerTimeRange: selectRange
			}
		}
	})
	timeSelected.value = 1
	params.roles[speaker.handleItemIndex] = speaker.handleItem
	speaker.timeRangeVisible = false
}


// 点击选择会议日期
const clickConfirmMeetingDate = ({ selectedValues }) => {
	params.meetingDate = selectedValues.join('-')
	dateTime.visible = false
}
// 点击选择会议时间
const clickConfirmMeetingTime = ({selectedValues}) => {
	params.meetingTime = selectedValues.join(':') + ':00'
	dateTime.timeVisible = false
	startTime.value = selectedValues
}

const init = () => {
  detail.value = {}
	params.topic = ''
	params.meetingDate = ''
	params.meetingTime = ''
	params.type = ''
	params.roles = []

	apply.visible = true
	getMeetingSetting()
	getSpeakerList()
}
// 点击申请会议
const clickApplyMeeting = () => init()

const submitSave = () => {
  showConfirmDialog({
		title: '温馨提示',
		message: '确定申请这场会议么？'
	}).then(() => {
		const list = []
		params.roles.forEach(item => {
			(item.list || []).forEach(val => {
				list.push({
					...item,
					...val,
					list: ''
				})
			})
		})
		return api.meetingApply({
			projectId: store.getters['user/getUserInfo'].projectId,
			topic: params.topic,
			meetingTime: `${params.meetingDate} ${params.meetingTime}`,
			type: params.type,
      		meetingAddr: params.meetingAddr,
			speakerJson: JSON.stringify(list)
		})
	}).then(res => {
		if (!res.code) {
			showToast('申请成功')
			emits('refresh')
			apply.visible = false
		}
	}).catch(err => {
		console.log(err)
	})
}

const submitUpdate = () => {
  showConfirmDialog({
		title: '温馨提示',
		message: '确定修改本次会议信息么？'
	}).then(() => {
		const list = []
		params.roles.forEach(item => {
			(item.list || []).forEach(val => {
				list.push({
					...item,
					...val,
					list: ''
				})
			})
		})
		return api.meetingUpdate({
			...detail.value,
			topic: params.topic,
			meetingTime: `${params.meetingDate} ${params.meetingTime}`,
			type: params.type,
      meetingAddr: params.meetingAddr,
			speakerJson: JSON.stringify(list)
		})
	}).then(res => {
		if (!res.code) {
			showToast('保存成功')
			emits('refresh')
			apply.visible = false
		}
	}).catch(err => {
		console.log(err)
	})
}
// 点击提交
const clickSubmit = (item) => {
  if (detail.value.id) {
    submitUpdate();
  } else {
    submitSave();
  }
}

const getDetail = async (id) => {
	const res = await api.meetingDetail(id)
	if (!res.code) {
		detail.value = res.data

    const meetingDateTime = res.data.meetingTime.split(' ')
    params.topic = res.data.topic || ''
    params.meetingDate = meetingDateTime[0]
    params.meetingTime = meetingDateTime[1]
    params.type = res.data.type
    params.meetingAddr = res.data.meetingAddr

    apply.visible = true
    getMeetingSetting();
	}
}
defineExpose({
  init,
  edit (id) {
    getDetail(id);
    getSpeakerList();
  }
})
</script>
